#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 反向迭代
问题: 你想反方向迭代一个序列
提示 : 
    1. 定义一个反向迭代器可以使得代码非常的高效
"""

def recipe1():
    """内置的 reversed() 函数"""
    a = [1, 2, 3, 4]
    for x in reversed(a):
        print(f"{x = }")

def recipe2():
    f = open(r'../somefile.txt')
    for line in reversed(list(f)):
        print(line, end='')
def recipe3():
    cd = Countdown(5)
    for rr in reversed(cd):
        print(f"{rr = }")

    for c in cd:
        print(f"{c = }")

class Countdown:
    """实现 __reversed__() 方法来实现反向迭代"""
    def __init__(self, start) -> None:
        self.start = start

    def __iter__(self):
        n = self.start
        while n > 0:
            yield n
            n -= 1

    def __reversed__(self):
        n = 1
        while n <= self.start:
            yield n
            n += 1

def main():
    print('recipe1'.center(20, '*'))
    recipe1() 
    print('recipe2'.center(20, '*'))
    recipe2() 
    print('recipe3'.center(20, '*'))
    recipe3() 

if __name__ == '__main__':
    main()             

